終於到,好好玩排序法了,好ㄟ。
Kotlin 中常見的排序算法包括以下幾種:
val numbers = listOf(5, 3, 1, 4, 2)
val sortedNumbers = numbers.sorted()
val numbers = listOf(5, 3, 1, 4, 2)
val sortedNumbers = numbers.sorted()
val numbers = mutableListOf(5, 3, 1, 4, 2)
for (i in 1 until numbers.size) {
val current = numbers[i]
var j = i - 1
while (j >= 0 && numbers[j] > current) {
numbers[j + 1] = numbers[j]
j--
}
numbers[j + 1] = current
}
val numbers = mutableListOf(5, 3, 1, 4, 2)
for (i in 0 until numbers.size - 1) {
var minIndex = i
for (j in i + 1 until numbers.size) {
if (numbers[j] < numbers[minIndex]) {
minIndex = j
}
}
val temp = numbers[i]
numbers[i] = numbers[minIndex]
numbers[minIndex] = temp
}
泡沫排序是一種簡單易實現的排序算法,但對於大型數據集來說效率較低,因為其時間複雜度為 O(n^2),其中 n 是數據集的大小。因此,在實際應用中,對於大型數據集,通常選擇更高效的排序算法,如快速排序或合併排序。
fun bubbleSort(arr: IntArray) {
val n = arr.size
var swapped: Boolean
do {
swapped = false
for (i in 0 until n - 1) {
if (arr[i] > arr[i + 1]) {
// 交換元素
val temp = arr[i]
arr[i] = arr[i + 1]
arr[i + 1] = temp
swapped = true
}
}
} while (swapped)
}
fun main() {
val numbers = intArrayOf(5, 3, 1, 4, 2)
bubbleSort(numbers)
println("排序後的數組:${numbers.joinToString()}")
}